import {Row, Col, Button, Space, Table, Form, Upload} from 'antd'
import {connect, history, useModel} from 'umi'
import React, {useEffect, useState} from 'react'
import Info from '../child/info'
import TableInfo from '../child/tableInfo'
import {FormInput, FormSelect} from '@/components/SearchForm/SearchFormItem'
import page from '../../page.less'
import {GlobalState} from '@/models/global'
import {refund, accountsReceivableInfo} from '@/service/fiance/index'
import {uploadFileUrl} from '@/service/common/upload'
import {getDict} from '@/service/common/dict'

const formLayout = {
	labelCol: {
		xs: {span: 24},
		sm: {span: 4},
	},
	wrapperCol: {
		xs: {span: 24, offset: 0},
		sm: {span: 12, offset: 0},
	},
}
export interface FixedBarProps {
	global: GlobalState
	dispatch: any
	location: any
}
function ReturnCost({
	global: {currentRoute},
	dispatch,
	location,
}: FixedBarProps) {
	const {
		query: {id},
	} = location
	const [info, setInfo] = useState({
		plateNo: '',
		refundNo: '',
		driverName: '',
		companyName: '',
		refundTypename: '',
		rentTypename: '',
		logListDtoList: [],
		flowList: [
			{transactionNo: '', paidMethodsname: '', remark: '', urlList: []},
		],
		refundStatusname: '',
	})
	const returnableInfo = [
		{label: '车牌号', value: info?.plateNo},
		{label: '应退单号', value: info?.refundNo},
		{label: '司机名称', value: info?.driverName},
		{label: '所属公司', value: info?.companyName},
		{label: '退款类型', value: info?.refundTypename},
		{label: '租赁类型', value: info?.rentTypename},
	]
	const [form] = Form.useForm()
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [oldFileList, setOldFileList] = useState<any>([]) // 上传文件
	const [deductionColumnsList, setDeductionColumnsList] = useState<any>([]) // 扣款费用数据
	const [freeColumnsList, setFreeColumnsList] = useState<any>([]) // 减免费用数据
	const [deductionColumns, setDeductionColumns] = useState<any>([]) // 扣款费用
	const [freeColumns, setFreeColumns] = useState<any>([]) // 收款费用
	const [expenseDetails, setExpenseDetails] = useState(0) // 费用明细总和
	const [expenseStatus, setExpenseStatus] = useState('') // 费用明细显示文字状态
	const [dict, setDict] = useState({
		order_finance_pey_type: [],
	}) // 字典值
	const [refundName, setRefundName] = useState()

	//  文件上传
	const uploadPropsOld = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file 测试上传:files
		data: {
			modelName: 'receivables',
			targetAttr: 1,
		},
		onChange(e: any) {
			if (e.file.status === 'done') {
				setOldFileList(e?.fileList)
				const list: any = []
				e?.fileList?.map((res: any) =>
					list.push(res?.response?.data?.id?.toString()),
				)
				form.setFieldsValue({urlList: list})
			}
			setOldFileList(e?.fileList)
		},
		oldFileList,
	}
	// 退款方式选择
	const selechChange = (_text: any, option: any) => {
		setRefundName(option?.dictValue)
	}
	// 提交
	const finish = (value: any) => {
		const info3 = {...value}
		info3.refundId = id
		info3.paidTypename = refundName
		info3.urlList = form.getFieldValue('urlList')
		refund(info3).then((res: any) => {
			if (res.success) {
				history.goBack()
			}
		})
	}
	useEffect(() => {
		accountsReceivableInfo({id}).then((res: any) => {
			setInfo(res?.data)
			const list1: any[] = []
			const list2: any[] = []
			const list5: any[] = []
			const list6: any[] = []
			let num1 = 0
			let num2 = 0
			let option1 = {}
			let option2 = {}
			// eslint-disable-next-line no-shadow
			res?.data?.orderSettlementFeeList?.forEach((res: any) => {
				if (res.feeType === 1) {
					res[res.feeItemName] = res.feeItemAmount
					option1 = {...option1, ...res}
					list5.push(res)
					num1 += Number(res?.feeItemAmount)
				} else {
					res[res.feeItemName] = res.feeItemAmount
					option2 = {...option2, ...res}
					list6.push(res)
					num2 += Number(res?.feeItemAmount)
				}
			})
			const obj = {
				合计: num1?.toFixed(2),
			}
			const obj1 = {
				合计: num2?.toFixed(2),
			}
			option1 = {...option1, ...obj}
			option2 = {...option2, ...obj1}
			list1.push(option1)
			list2.push(option2)
			if (num1 - num2 > 0) {
				setExpenseDetails(num1 - num2)
				setExpenseStatus('需要客户补缴金额/元')
			} else {
				setExpenseDetails(num2 - num1)
				setExpenseStatus('需要退还客户金额/元')
			}
			setDeductionColumnsList(list1)
			setFreeColumnsList(list2)
			const list3: any[] = []
			const list4: any[] = []
			list5?.forEach((ress: any) => {
				const obj3 = {
					title: ress?.feeItemName,
					dataIndex: ress?.feeItemName,
				}
				list3.push(obj3)
			})
			const obj2 = {
				title: '合计',
				dataIndex: '合计',
			}
			list3.push(obj2)
			setDeductionColumns(list3)
			list6?.forEach((rest: any) => {
				const obj4 = {
					title: rest?.feeItemName,
					dataIndex: rest?.feeItemName,
				}
				list4.push(obj4)
			})
			list4.push(obj2)
			setFreeColumns(list4)
		})
		getDict(
			{
				dictKeys: [
					'order_finance_pey_type', // 退款方式
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	return (
		<div className={page.page}>
			<Info title="退款单信息" info={returnableInfo} span={8} />
			<TableInfo
				state={{label: expenseStatus, value: expenseDetails}}
				columns={deductionColumns}
				title="费用明细"
				tableTitle="扣款费用项"
				pagination={false}
				dataSource={deductionColumnsList}>
				<Table
					bordered
					// title={() => <span>减免费用项</span>}
					columns={freeColumns}
					pagination={false}
					dataSource={freeColumnsList}
					style={{marginTop: '10px'}}
				/>
			</TableInfo>

			<div className={`${page.page} ${page.card}`}>
				<p className={page.dotTitle}>收款操作</p>
				<Form
					name="basic"
					onFinish={finish}
					onFinishFailed={() => {}}
					autoComplete="off"
					{...formLayout}
					wrapperCol={{flex: 1}}>
					<Row gutter={24}>
						<Col span={24}>
							<FormInput
								name="transactionNo"
								label="交易流水号"
								rules={[
									{
										required: true,
										message: '请输入交易流水号',
									},
								]}
								style={{width: '300px'}}
								placeholder="请输入交易流水号"
							/>
						</Col>
						<Col span={24}>
							<FormSelect
								label="退款方式"
								placeholder="请选择退款方式"
								name="paidType"
								keys="dictKey"
								title="dictValue"
								items={dict?.order_finance_pey_type}
								onChange={selechChange}
								rules={[
									{
										required: true,
										message: '请选择退款方式',
									},
								]}
								style={{width: '300px'}}
							/>
						</Col>
						<Col span={24}>
							<FormInput
								name="remark"
								label="备注"
								style={{width: '600px'}}
								placeholder="请填写退款备注，不超过200个字符"
								rules={[
									{
										max: 200,
										message: '备注不得超过200个字符',
									},
								]}
							/>
						</Col>
						<Col span={24}>
							<Form.Item name="urlList" label="退款凭怔">
								<Upload {...uploadPropsOld}>
									{oldFileList?.length >= 5 ? null : (
										<Button>添加附件</Button>
									)}
								</Upload>
								<p style={{margin: '15px 0 0 0'}}>
									附件说明：附件最大支持30M，
								</p>
								<p>支持格式：PDF、Word、Excel、JPG、PNG</p>
							</Form.Item>
						</Col>
					</Row>
					<Row justify="center" style={{marginTop: '20px'}}>
						<Form.Item>
							<Space>
								<Button
									shape="round"
									onClick={(e) => {
										e.stopPropagation()
										dispatch({
											type: 'global/deleteTabs',
											payload: currentRoute,
										})
										history.goBack()
									}}>
									取消
								</Button>
								<Button
									shape="round"
									type="primary"
									htmlType="submit">
									提交
								</Button>
							</Space>
						</Form.Item>
					</Row>
				</Form>
			</div>
		</div>
	)
}

export default connect(({global}: any) => ({global}))(ReturnCost)
